* Generate Figures 1, 5 (left panel), A.7 (left panel), B.1, B.2, B.4, and B.5.

* Locals: `1' is `outputfolder', `2' is `GraphsByEpi', `3' is `windowstart', and `4' is `windowend'

* Adjustments of overlap in pre and post devaluation windows
sort ccode largeDevaluation year
bys ccode largeDevaluation: gen episodeC = _n
replace episodeC=. if largeDevaluation==.
qui su episodeC
local max_epiC=`r(max)'

forval i=1/`max_epiC'{
gen indicator = 0
replace indicator=1 if episodeC==`i'
gen yearEpiC_temp = indicator * year if episodeC==`i'
bys ccode: egen yearEpiC`i' = total(yearEpiC_temp)
drop indicator yearEpiC_temp
replace yearEpiC`i'=. if yearEpiC`i'==0
gen normyearEpiC`i'= year - yearEpiC`i'
replace normyearEpiC`i'=. if normyearEpiC`i'>`4' | normyearEpiC`i'<`3'
}

sort ccode year
	
* Expand the data to allow multiple episodes by country:
merge m:1 ccode using "temp/Numb Events by Country.dta"
drop if _merge==1 // countries without any events
drop _merge

levelsof ccode, local(CountryList)
foreach n of local CountryList {
preserve
keep if ccode=="`n'"
local factor = numbepi[1]
restore
expand `factor'	if ccode=="`n'"
}

* Create episode identifier and period (normyear) variable:
sort ccode year
bys ccode year: gen episode=_n
merge m:1 ccode episode using "temp/Depreciation Events.dta"
drop _merge
gen normyear=year-devaluationYear		
egen epi = group(ccode episode)
	
* Growth rates relative to pre devaluation year 
foreach var in importshare importshare2 rer rerPWT exportshare rer_cpi MIMD MIMD2 e1 SXSD {
gen temp=`var' if normyear==-1
by ccode episode, sort: egen base=max(temp)
gen rel`var'=(`var'/base-1)*100
drop temp base
}

* Adjustments due to transition of data in 1995 from JN to WIOD/OECD for some events // omitting these changes has minimal effects
* For events in 1996-2000, set variables to missing when period is prior to 1995
gen T_temp=0
replace T_temp=1 if largeDevaluation==1  & year<=2000 & year>1995 & importshare!=importshare2 & devaluationYear==year // WIOD/OECD available
bys ccode episode: egen T =total(T_temp)
foreach var in relimportshare2 relrer relrerPWT relexportshare relrer_cpi relMIMD relMIMD2 {
replace `var' =. if normyear>=`3' & normyear<=`4' & year<1995 & T==1
}

* For events in 1990-1995, when WIOD/OECD available, use import share and relative spending from JN for periods post 1995 to ensure continuity
gen T_temp2=0
replace T_temp2=1 if largeDevaluation==1  & year<=1995 & year>=1990 & devaluationYear==year // WIOD/OECD available
bys ccode episode: egen T2 =total(T_temp2)
replace relimportshare2 =relimportshare if normyear>=`3' & normyear<=`4' & year>=1995 & T2==1 & importshare!=.
replace relMIMD2 =relMIMD if normyear>=`3' & normyear<=`4' & year>=1995 & T2==1 & importshare!=.

* Figure 1
* Event-level indicator for episodes of Figure 1
gen appr_temp =0 
replace appr_temp = 1 if normyear==0 & year==2002 & ccode=="ARG" | normyear==0 & year==1999 & ccode=="BRA" | normyear==0 & year==1998 & ccode=="IDN" ///
| normyear==0 & year==1997 & ccode=="KOR" | normyear==0 & year==1998 & ccode=="MYS" | normyear==0 & year==1998 & ccode=="RUS" ///
| normyear==0 & year==1998 & ccode=="THA" 

bys ccode episode: egen recent = total(appr_temp)

preserve
keep if recent==1 & normyear==0
gen recent_id = _n
keep ccode episode recent_id
save "temp/recent_id.dta", replace
restore	

merge m:1 ccode episode using "temp/recent_id.dta"
drop _merge 

set more off
set graphics on

preserve
	keep if recent==1
	keep if normyear>=`3' & normyear<=`4'
	sort ccode year
	collapse (mean) relimportshare relimportshare2 relrer relrerPWT relexportshare relrer_cpi, by(normyear)
	label var normyear "Year Since Devaluation"
	label var relrer_cpi "IFS CPI RER"
	label var relrer "IFS RER"
	label var relrerPWT "PWT RER"
	label var relimportshare "Imported Input Share Growth"
	label var relimportshare2 "Imported Input Share Growth"
	label var relexportshare "Export Share Growth"
	save "temp/F1_recent_means.dta", replace
restore

preserve
	keep if recent==1
	keep if normyear>=`3' & normyear<=`4'
	collapse (semean) relimportshare relimportshare2 relrer relrerPWT relexportshare relrer_cpi, by(normyear)	
	foreach var in relimportshare relimportshare2 relrer relrerPWT relexportshare relrer_cpi {
	ren `var' `var'_se
	}	
	save "temp/F1_recent_se.dta", replace
restore
	
* Put means and SE together for F1:
preserve
	use "temp/F1_recent_means.dta",clear
	merge 1:1 normyear using "temp/F1_recent_se.dta"
	gen up = relimportshare2 + relimportshare2_se
	gen down = relimportshare2 - relimportshare2_se
	gen up_rer = relrer + relrer_se
	gen down_rer = relrer - relrer_se	
			
	tw (line relimportshare2 normyear, lc(blue) lw(thick)) ///
	   (line up normyear, lpattern(shortdash) lwidth(vthin) lc(blue)) (line down normyear, lpattern(shortdash) lwidth(vthin) lc(blue)) ///
	   (scatter relrer normyear, c(l) color(red) ms(X) msize(medlarge) lw(thick)) ///
	   (line up_rer normyear, lpattern(shortdash) lwidth(vthin) lc(red)) (line down_rer normyear, lpattern(shortdash) lwidth(vthin) lc(red)) ///
	   ,yline(0,lc(black)) xline(0,lc(black) lpattern(dash))  xt("Year Since Devaluation") yt("Percent Change") /// 
	   graphregion(margin(l=0 r=0 b=0 t=0)) graphregion(color(white)) ///
	   legend(off) scale(1.2) ///
	   text(-15 -1.3  "RER", color(red) size(small)) /// 
	   text(20 -1.3 "Import" "Share", color(blue) size(small)) /// 
	   xlab(`3'(1)`4') 
	graph export "`1'/F1.pdf", replace
restore
	
* Adjust data for overlapping events
* Note: skipping these steps has a small impact on Figure 2
qui do "Analysis_dofiles/Overlap.do"
	
* By Episode
if `2'==1{
egen distinct=group(ccode episode)
su distinct, meanonly
set more off
set graphics on
foreach i of num 1/`r(max)' {
preserve
	keep if distinct==`i'
	keep if normyear>=`3' & normyear<=`4'
	local cnamelong = country[1]
	local cname = ccode[1]
	local year = devaluationYear[1]
	sort normyear
	tw (line relimportshare2 normyear, lc(blue) lw(thick)) ///
	   (scatter relrer normyear, c(l) color(red) ms(X) msize(medlarge) lw(thick)) ///
	   ,yline(0,lc(black)) xline(0,lc(black) lpattern(dash))   /// 
	   graphregion(margin(l=0 r=0 b=0 t=0)) graphregion(color(white)) xtitle("") title("`cnamelong', `year'") ///
	   legend(off) scale(1) name(G`i') ///
	   xlab(`3'(1)`4') 
	 
	 if `i'==6{
	 qui graph export "`1'/FA7_A.pdf", replace
	 }
restore
}
graph combine G1 G2 G3 G4 G5 G6 G7 G8 G9 G10 G11 G12 G13 G14 G15 G16 G17 G18 G19 G20 ///
			  G21 G22 G23 , graphregion(color(white))
qui graph export "`1'/FB1.pdf", replace 
graph combine G24 G25 G26 G27 G28 G29 G30 G31 G32 G33 G34 G35 G36 G37 G38 G39 G40 ///
			  G41 G42 G43  , graphregion(color(white))
qui graph export "`1'/FB2.pdf", replace 					  
graph drop _all
}
	
* Focus on window around events
keep if normyear>=`3' & normyear<=`4'
	
* Series of collapses for Figures 2 and 5
set graphics on
preserve
	collapse (mean) relimportshare relimportshare2 relrer relrerPWT rele1 relexportshare relrer_cpi relMIMD, by(normyear)
	label var normyear "Year Since Devaluation"
	label var relrer_cpi "IFS CPI RER"
	label var relrer "IFS RER"
	label var relrerPWT "PWT RER"
	label var relimportshare "Imported Input Share Growth"
	label var relimportshare2 "Imported Input Share Growth"
	label var relexportshare "Export Share Growth"
	save "temp/F2_means.dta", replace
restore
preserve
	collapse (semean) relimportshare relimportshare2 relrer relrerPWT rele1  relexportshare relrer_cpi, by(normyear) 
	foreach var in relimportshare relimportshare2 relrer relrerPWT  relexportshare relrer_cpi { 
	ren `var' `var'_se
	}	
	save "temp/F2_se.dta", replace
restore

*. Put means and SE together for Figures 2 and 5
preserve
	use "temp/F2_means.dta",clear
	merge 1:1 normyear using "temp/F2_se.dta"
	gen up = relimportshare2 + relimportshare2_se
	gen down = relimportshare2 - relimportshare2_se
	gen up_rer = relrer + relrer_se
	gen down_rer = relrer - relrer_se	
	* Figure 2
	graph set window fontface "Times"
	tw (line relimportshare2 normyear, lc(blue) lw(thick)) ///
	   (line up normyear, lpattern(shortdash) lwidth(vthin) lc(blue)) (line down normyear, lpattern(shortdash) lwidth(vthin) lc(blue)) ///
	   (scatter relrer normyear, c(l) color(red) ms(X) msize(medlarge) lw(thick)) ///
	   (line up_rer normyear, lpattern(shortdash) lwidth(vthin) lc(red)) (line down_rer normyear, lpattern(shortdash) lwidth(vthin) lc(red)) ///
	  ,yline(0,lc(black)) xline(0,lc(black) lpattern(dash))  xt("Year Since Devaluation") yt("Percent Change") /// 
	  graphregion(margin(l=0 r=0 b=0 t=0)) graphregion(color(white)) ///
	  legend(off) scale(1.2) ///
	  text(-15 -1  "RER", color(red) size(small)) /// 
	  text(10 -1 "Import" "Share", color(blue) size(small)) ///	  
	  xlab(`3'(1)`4') 
	
	graph export "`1'/F2.pdf", replace
	
	* Figure 5, left panel (aggregate export share):
	gen up_sx = relexportshare + relexportshare_se
	gen down_sx = relexportshare - relexportshare_se
	
	tw  (line relexportshare normyear, lc(blue) lw(thick)) ///
	(line up_sx normyear, lpattern(shortdash) lwidth(vthin) lc(blue)) (line down_sx normyear, lpattern(shortdash) lwidth(vthin) lc(blue)) ///
	(scatter relrer normyear, c(l) color(red) ms(X) msize(medlarge) lw(thick)) ///
	(line up_rer normyear, lpattern(shortdash) lwidth(vthin) lc(red)) (line down_rer normyear, lpattern(shortdash) lwidth(vthin) lc(red)) ///
	,yline(0,lc(black)) xline(0,lc(black) lpattern(dash))  xt("Year Since Devaluation") yt("Percent Change") /// 
	graphregion(color(white)) graphregion(margin(l=0 r=0 b=0 t=0)) ///
	legend(off) scale(1.2) ///
	text(-15 -1  "RER", color(red) size(small)) /// 
	text(23 -1 "Export" "Share", color(blue) size(small)) /// 
	xlab(`3'(1)`4') ylabel(-30 0 30 60) yscale(range(-35 75)) 
	graph export "`1'/F5_A.pdf", replace
	
	* Figure B.4 (JN data only)
	gen upJN = relimportshare + relimportshare_se
	gen downJN = relimportshare - relimportshare_se
	
	tw (line relimportshare normyear, lc(blue) lw(thick)) /// Note: relimportshare instead of relimportshare2
	(line upJN normyear, lpattern(shortdash) lwidth(vthin) lc(blue)) (line downJN normyear, lpattern(shortdash) lwidth(vthin) lc(blue)) ///
	(scatter relrer normyear, c(l) color(red) ms(X) msize(medlarge) lw(thick)) ///
	(line up_rer normyear, lpattern(shortdash) lwidth(vthin) lc(red)) (line down_rer normyear, lpattern(shortdash) lwidth(vthin) lc(red)) ///
	, yline(0,lc(black)) xline(0,lc(black) lpattern(dash))  xt("Year Since Devaluation") yt("Percent Change") /// 
	graphregion(margin(l=0 r=0 b=0 t=0)) graphregion(color(white)) ///
	legend(off) scale(1.2) ///
	text(-15 -1  "RER", color(red) size(small)) /// 
	text(10 -1 "Import" "Share", color(blue) size(small)) /// 
	xlab(`3'(1)`4') 
	graph export "`1'/FB4.pdf", replace
	
	* Figure B.5 (alternative RER Measures)	
	tw (line relrer normyear, lc(red) lw(thick)) /// Bilateral (baseline)
	(scatter rele1 normyear, c(l) color(gray) ms(o) msize(medlarge) lw(thick)) /// Effective
	(scatter relrerPWT normyear, c(l) color(orange) ms(X) msize(medlarge) lw(thick)) /// PWT
	(scatter relrer_cpi normyear, c(l) color(green) ms(X) msize(medlarge) lw(thick)) /// Bilateral CPI
	,yline(0,lc(black)) xline(0,lc(black) lpattern(dash))  xt("Year Since Devaluation") yt("Percent Change") /// 
	graphregion(margin(l=0 r=8 b=0 t=0)) graphregion(color(white)) ///
	legend(off) scale(1.2) ///
	text(-15.3 8  "Bilateral (PPI)", color(red) size(small)) /// 
	text(-18.3 8  "Bilateral (CPI)", color(green) size(small)) /// 
	text(-10.3 8 "PWT", color(orange) size(small)) /// 
	text(-12.6 8 "Effective", color(gray) size(small)) /// 	
	xlab(`3'(1)`4') 
	graph export "`1'/FB5.pdf", replace
	
	if 1==0{ // Run these lines to generate a version of Figure 2 with the CPI-based RER
	gen up_rer_cpi = relrer_cpi + relrer_cpi_se
	gen down_rer_cpi = relrer_cpi - relrer_cpi_se	
	tw (line relimportshare2 normyear, lc(blue) lw(thick)) ///
	(line up normyear, lpattern(shortdash) lwidth(vthin) lc(blue)) (line down normyear, lpattern(shortdash) lwidth(vthin) lc(blue)) ///
	(scatter relrer_cpi normyear, c(l) color(red) ms(X) msize(medlarge) lw(thick)) ///
	(line up_rer_cpi normyear, lpattern(shortdash) lwidth(vthin) lc(red)) (line down_rer_cpi normyear, lpattern(shortdash) lwidth(vthin) lc(red)) ///
	,yline(0,lc(black)) xline(0,lc(black) lpattern(dash))  xt("Year Since Devaluation") yt("Percent Change") /// 
	graphregion(margin(l=0 r=0 b=0 t=0)) graphregion(color(white)) ///
	legend(off) scale(1.2) ///
	text(-15 -1  "RER", color(red) size(small)) /// 
	text(10 -1 "Import" "Share", color(blue) size(small)) /// 		  
	xlab(`3'(1)`4') 
	graph export "`1'/F2_CPI.pdf", replace
	}
restore

* Compute statistics needed for Figure 5 (right panel)
* compute average export growth in post appreciation sample
gen dumi = 0 if relexportshare!=.
replace dumi=1 if normyear>=0
bys ccode episode dumi: egen avgXgrowth = mean(relexportshare)
replace avgXgrowth=. if dumi==0

* compute average import growth in post appreciation sample	
bys ccode episode dumi: egen avgMgrowth = mean(relimportshare2)
replace avgMgrowth=. if dumi==0

* country-episode level indicator of strength export expansion
preserve
keep if normyear==1
drop if avgXgrowth==.
sum avgXgrowth, de
_pctile avgXgrowth, p(50)
local median=`r(r1)'
keep ccode episode devaluationYear avgXgrowth avgMgrowth
sort ccode episode
save "temp/vars_for_PVSQ.dta", replace
restore

merge m:1 ccode episode using "temp/vars_for_PVSQ.dta"
